package com.example.myapplication.tool;

import android.text.TextUtils;

import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OKHttpTool {
    public static String URL = "http://124.93.196.45:10001";
    public static String TOKEN = "";
    public static String GET = "get";
    public static String POST = "post";
    public static String PUT = "put";
    private static OkHttpClient okHttpClient;
    private static Gson gson;
    private static void init(){
        gson = null;
        okHttpClient = null;
        okHttpClient = new OkHttpClient();
        gson = new  Gson();
    }
    public static void doRequest(String url,String method,Class clazz,NetClick netClick,String... JSONObject){
        Request.Builder rb = new Request.Builder();
        if(!TextUtils.isEmpty(url)){
            url = URL =url;
            rb.url(url);
        }
        if(!TextUtils.isEmpty(TOKEN)){
            rb.addHeader("Authorization",TOKEN);
        }
        if(GET.equals(method)){
            rb.get();
        }
        if(POST.equals(method) && JSONObject.length >0){
            rb.post(RequestBody.create(JSONObject[0], MediaType.parse("application/json;")));
        }
        if(PUT.equals(method) && JSONObject.length >0){
            rb.put(RequestBody.create(JSONObject[0], MediaType.parse("application/json;")));
        }
        if(okHttpClient == null || gson == null){
            init();
        }
        Request request = rb.build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                netClick.onFail("onFailure  请求失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String json = response.body().string();
                Object obj = gson.fromJson(json, clazz);
                try{
                    netClick.onSuccess(obj);

                }catch (Exception e){
                    netClick.onFail("onResponse  请求失败");
                }
            }
        });

    }

    public interface NetClick{
        Void onFail(String msg);
        void onSuccess(Object obj);
    }
}
